import {
    postLogin
} from '@/api/login'
import {
    getUserData
} from '@/api/user'
import {
    setToken,
    getToken,
    removeToken,
    getCookieValue
} from '@/utils/auth'

const user = {
    state: {
        // token: getToken(),
        token: getCookieValue("username"),
        userid: '',
        username: '',
        avatar: '',
        roles: []
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ID: (state, id) => {
            state.userid = id
        },
        SET_NAME: (state, username) => {
            state.username = username
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },
    actions: {
        Login({
            commit,
            state,
        }, data) {
            return new Promise((resolve, reject) => {
                postLogin(data).then(ret => {
                    setToken(ret.data.username)
                    resolve(ret)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        GetInfo({
            commit,
            state
        }) {
            return new Promise((resolve, reject) => {
                getUserData().then(ret => {
                    console.log(ret);
                    if (ret.state == 200) {
                        if (ret.data.roles.length > 0) {
                            commit('SET_ROLES', ret.data.roles);
                        } else {
                            reject("user has no roles");
                        }
                        commit('SET_ID', ret.data.user_id)
                        commit('SET_NAME', ret.data.username)
                        commit('SET_AVATAR', ret.data.avatar)
                        resolve(ret);
                    }
                }).catch(err => {
                    reject(err);
                })
            })
        },
        FedLogOut({
            commit
        }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user